package sg.techstudio.suntec.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import javax.servlet.http.HttpSession;

import org.springframework.ui.Model;


public abstract class BaseController {
	public static final String SPRING_EXT = ".sw";
	public static final String SPRING_REDIRECT_PREFIX = "redirect:/";
	
	public static final String PARAM_ERRMSG 		= "errmsg";
	public static final String PARAM_PAGE 			= "page";
	public static final String PARAM_ID				= "id";
	
	public static final String PARAM_CONTENT_LIST	= "contentList";
	public static final String PARAM_ROLE_LIST		= "roleList";
	public static final String PARAM_MODULE_LIST	= "moduleList";
	
	public static final String SESSION_ATTR_ROLE	= "role";
	
	protected static final DateFormat SDF_DD_MM_YYYY = new SimpleDateFormat("dd/MM/yyyy" );
	protected static final DateFormat SDF_LONG = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss" );
	
	/**
	 * 
	 * @return subfolder located in "/WEB-INF/views/" for this current module
	 */
	protected abstract String getModuleFolder();
	
	protected String redirectToPageSpring(String strURL) {
		return SPRING_REDIRECT_PREFIX + strURL;
	}
	
	protected String goToPageJsp(String strURL) {
		return getModuleFolder() + strURL;
	}
		
	protected boolean isLogin(HttpSession session, Model model) {
		if(session.getAttribute(SESSION_ATTR_ROLE)!=null)
			return true;
		addError(model, "Your session has expired. Please login again.");
		return false;
	}
	
	protected String getLoginPath() {
		return "login"+SPRING_EXT;
	}
	
	protected String getRedirectedLoginPath() {
		return getRedirectedLoginPath(true);
	}
	
	protected String getRedirectedLoginPath(boolean toTimeoutpage) {
		return toTimeoutpage?SPRING_REDIRECT_PREFIX+"timeout"+SPRING_EXT:SPRING_REDIRECT_PREFIX+getLoginPath();
	}
	
	protected void addError(Model model, String msg) {
		model.addAttribute(PARAM_ERRMSG, msg);
	}
	
	protected boolean hasErrorMsg(Model model) {
		return model!=null && model.containsAttribute(PARAM_ERRMSG);
	}
	
	private static final Pattern EMAIL_PATTERN = Pattern.compile("\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b", Pattern.CASE_INSENSITIVE);
	public static boolean isValidEmail(String email) {
		return email!=null && EMAIL_PATTERN.matcher(email).matches();
	}
	
	protected String formatDateColumn(Date d) {
		if(d==null)
			return "";
		return SDF_LONG.format(d);
	}
}
